package org.lyg.controller;

import com.github.pagehelper.PageInfo;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.ExpiredCredentialsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.SavedRequest;
import org.apache.shiro.web.util.WebUtils;
import org.lyg.domain.Blog;
import org.lyg.domain.BlogCondition;
import org.lyg.domain.User;
import org.lyg.service.IBlogService;
import org.lyg.service.IUserService;
import org.lyg.validation.First;
import org.lyg.validation.Second;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    IUserService userService;
    @Autowired
    IBlogService blogService;

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(ModelMap modelMap) {
        Object o = modelMap.get("user");
        System.out.println(o);
        modelMap.addAttribute("user", new User());
        return "login";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(@Validated(First.class) User user, BindingResult bindingResult, HttpServletRequest request, ModelMap model) {
        if (bindingResult.hasErrors()) {
            return "login";
        }
        UsernamePasswordToken token = new UsernamePasswordToken(user.getName(), user.getPwd());
        token.setRememberMe(true);
        Subject subject = SecurityUtils.getSubject();
        String msg = "";
        try {
            subject.login(token);
            if (subject.isAuthenticated()) {
                request.getSession().setAttribute("user", user);
                SavedRequest savedRequest = WebUtils.getSavedRequest(request);
                // 获取保存的URL
                if (savedRequest == null || savedRequest.getRequestUrl() == null) {
                    System.out.println("home");
                    return "redirect:/home";
                } else {
                    System.out.println("pre");
                    //String url = savedRequest.getRequestUrl().substring(12, savedRequest.getRequestUrl().length());
                    return "redirect:" + savedRequest.getRequestUrl();
                }
            }
        } catch (IncorrectCredentialsException e) {
            msg = "登录密码错误. Password for account " + token.getPrincipal() + " was incorrect.";
            model.addAttribute("message", msg);
            System.out.println(msg);
        } catch (ExcessiveAttemptsException e) {
            msg = "登录失败次数过多";
            model.addAttribute("message", msg);
            System.out.println(msg);
        } catch (LockedAccountException e) {
            msg = "帐号已被锁定. The account for username " + token.getPrincipal() + " was locked.";
            model.addAttribute("message", msg);
            System.out.println(msg);
        } catch (DisabledAccountException e) {
            msg = "帐号已被禁用. The account for username " + token.getPrincipal() + " was disabled.";
            model.addAttribute("message", msg);
            System.out.println(msg);
        } catch (ExpiredCredentialsException e) {
            msg = "帐号已过期. the account for username " + token.getPrincipal() + "  was expired.";
            model.addAttribute("message", msg);
            System.out.println(msg);
        } catch (UnknownAccountException e) {
            msg = "帐号不存在. There is no user with username of " + token.getPrincipal();
            model.addAttribute("message", msg);
            System.out.println(msg);
        } catch (UnauthorizedException e) {
            msg = "您没有得到相应的授权！" + e.getMessage();
            model.addAttribute("message", msg);
            System.out.println(msg);
        }
        model.addAttribute("loginFailed", msg);
        return "login";
    }

    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public String register() {
        return "register";
    }

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String register(@Validated(Second.class) User user, ModelMap modelMap, BindingResult bindingResult) {
        user.setCreateTime(new Date());
        modelMap.addAttribute("user", user);
        if (bindingResult.hasErrors()) {
            modelMap.addAttribute("msg", bindingResult.getAllErrors().get(0));
            return "register";
        }
        if (!userService.save(user)) {
            modelMap.addAttribute("msg", "注册失败！");
            return "register";
        }
        return "redirect:login";
    }

    @RequestMapping("/logout")
    public String logout(ModelMap modelMap) {
        try {
            SecurityUtils.getSubject().logout();
        } catch (Exception e) {
            e.printStackTrace();
        }
        modelMap.addAttribute("user", new User());
        return "login";
    }

    @RequestMapping("/center/{username}")
    public String center(@PathVariable("username") String username, ModelMap modelMap) {
        return center(username, 1, modelMap);
    }

    @RequestMapping("/center/{username}/list/{page}")
    public String center(@PathVariable("username") String username, @PathVariable("page") int page, ModelMap modelMap) {
        User user = userService.getUserByName(username);
        System.out.println(user);
        modelMap.addAttribute("u", user);
        User userSelf = (User) SecurityUtils.getSubject().getPrincipal();
        System.out.println(userSelf);
        modelMap.addAttribute("userSelf", userSelf);

        if (page <= 0) {
            page = 1;
        }

        PageInfo<Blog> blogPageInfo = blogService.list(2, page,new BlogCondition(null,null,user.getId(),false));
        modelMap.addAttribute("blogPageInfo", blogPageInfo);
        System.out.println(blogPageInfo);
        return "user/center";
    }

    @RequestMapping("/blog/del/{id}")
    public String blogDel(@PathVariable("id") int id) {
        blogService.del(id);
        return "redirect:/user/manager/list/1";
    }

    @RequestMapping("/manager/list/{page}")
    public String manager(@PathVariable("page") int page, ModelMap modelMap) {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        PageInfo<Blog> blogPageInfo = blogService.list(10,page, new BlogCondition(null,null,user.getId(),false));
        modelMap.addAttribute("blogPageInfo", blogPageInfo);
        modelMap.addAttribute("manager", true);
        modelMap.addAttribute("u", user);
        modelMap.addAttribute("userSelf", user);
        return "user/center";
    }

    @RequestMapping(value = "/update/pwd", method = RequestMethod.GET)
    public String updatePwd() {
        return "user/updatepwd";
    }

    @RequestMapping(value = "/update/pwd", method = RequestMethod.POST)
    public String updatePwd(String oldPwd, String newPwd,ModelMap modelMap) {
        if (StringUtils.isEmpty(oldPwd)||StringUtils.isEmpty(newPwd)){
            modelMap.addAttribute("msg","请输入合法参数！");
            return "user/updatepwd";
        }
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        if (user.getPwd().equals(oldPwd)) {
            user.setPwd(newPwd);
            System.out.println(user);
            userService.update(user);
        }
        SecurityUtils.getSubject().logout();
        return "redirect:/user/login";
    }
}
